//
//  UITextField+inputRule.m
//  SmartEstateCC
//
//  Created by 初唐科技 on 2018/7/17.
//  Copyright © 2018 pretang. All rights reserved.
//

#import "UITextField+inputRule.h"

@implementation UITextField (inputRule)
//限制输入小数点2位
- (BOOL)numberAndPointShowInfoView:(UIView *)infoView shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string maxLength:(NSInteger)maxLength
{
    BOOL isHavePoint = NO;
    if ([self.text rangeOfString:@"."].location==NSNotFound) {
        isHavePoint = NO;
    }
    else
    {
        isHavePoint = YES;
    }
    //输入字符 不是删除
    if ([string length]>0)
    {
        unichar single=[string characterAtIndex:0];//当前输入的字符
        if ((single >='0' && single<='9') || single=='.')//数据格式正确
        {
            //首字母不能为小数点
            if([self.text length]==0){
                if(single == '.'){
                    [infoView showInfo:@"第一个数字不能为小数点"];
                    [self.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                    
                }
            }
            //首字母为0的时候，如果再次输入整数，则移除首字母的0
            if ([self.text length]==1 && [self.text isEqualToString:@"0"]) {
                if (single != '.') {
                    self.text = @"";
                    return YES;
                }
            }
            //限制输入位数
            if (self.text.length >= maxLength) {
                [infoView showInfo:[NSString stringWithFormat:@"只能输入%ld个字符",maxLength]];
                return NO;
            }
            if (single=='.')
            {
                if(!isHavePoint)//text中还没有小数点
                {
                    isHavePoint=YES;
                    return YES;
                }else
                {
                    [infoView showInfo:@"您已经输入过小数点了"];
                    [self.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            else
            {
                if (isHavePoint)//存在小数点
                {
                    //判断小数点的位数
                    NSRange ran=[self.text rangeOfString:@"."];
                    int tt=range.location-ran.location;
                    if (tt <= 2){
                        return YES;
                    }else{
                        [infoView showInfo:@"您最多输入两位小数"];
                        return NO;
                    }
                }
                else
                {
                    return YES;
                }
            }
        }else{//输入的数据格式不正确
            [infoView showInfo:@"您输入的格式不正确"];
            [self.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    }
    else
    {
        return YES;
    }
    
}
@end
